package com.jeesuite.bestpl.exception;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public ResponseEntity<ErrorResponseEntity> exceptionHandler(Exception e, HttpServletResponse response) {
		ErrorResponseEntity resp = new ErrorResponseEntity();
		if (e instanceof JeesuiteBaseException) {
			JeesuiteBaseException e1 = (JeesuiteBaseException) e;
			resp.setErrorCode(e1.getCode());
			resp.setErrorMsg(e1.getMessage());
		} else if(e instanceof org.springframework.web.HttpRequestMethodNotSupportedException){
			resp.setErrorCode(HttpStatus.METHOD_NOT_ALLOWED.value());
			resp.setErrorMsg(e.getMessage()); 
		}else if(e instanceof org.springframework.web.HttpMediaTypeException){
			resp.setErrorCode(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value());
			resp.setErrorMsg(e.getMessage()); 
		}else {
			resp.setErrorCode(500);
			resp.setErrorMsg("系统繁忙");
			logger.error("",e);
		}
		return new ResponseEntity<ErrorResponseEntity>(resp,HttpStatus.OK);
	}
}